import { ref, watchEffect } from 'vue'

/**
 * 验证码倒计时
 * @param s 倒计时秒数
 * @returns
 */
export function useVerifyCode(s = 60) {
  const wait = ref(false)
  const time = ref(s)
  let timerId: number | null = null

  const reset = () => {
    if (timerId)
      clearInterval(timerId)
    time.value = s
    wait.value = false
  }

  watchEffect(() => {
    if (wait.value) {
      if (timerId)
        clearInterval(timerId)
      timerId = setInterval(() => {
        time.value--
        if (time.value <= 0) {
          wait.value = false
          time.value = s
          clearInterval(timerId!)
        }
      }, 1000) as unknown as number
    } else {
      time.value = s
      clearInterval(timerId!)
    }
  })

  onUnmounted(() => {
    timerId && clearInterval(timerId)
  })

  return { time, wait, reset }
}
